package cn.xiaolang.function.data_structure;

/**
 * @author fuhw/Dean
 * @date 2020-04-28
 */
public class RollingWindowMax {

    public static void main(String[] args) {
        int[] array = {-3, 3, 1, -3, 2, 4, 7};
        int n = 3;
        System.out.println(getSlideWindowMax(array, n));
    }

    /**
     *
     *
     * @param array
     * @param n
     * @return 获取数组中连续n个数之和最大值
     */
    private static int getSlideWindowMax(int[] array, int n) {
        if (array.length < n) {
            return 0;
        }
        int maxSum = 0;
        for (int i = 0; i < n; i++) {
            maxSum += array[i];
        }

        int windowSum = maxSum;

        for (int i = n; i < array.length; i++) {
            // 滑动窗口，加一个尾数 减一个头数
            windowSum += array[i] - array[i - n];
            maxSum = Math.max(maxSum, windowSum);
        }
        return maxSum;
    }
}
